<template>
  <n-form ref="formRef" :model="formValue" :rules="rules">
    <n-form-item label="姓名" path="user.name">
      <n-input v-model:value="formValue.user.name" placeholder="输入姓名" />
    </n-form-item>
    <n-form-item label="年龄" path="user.age">
      <n-input v-model:value="formValue.user.age" placeholder="输入年龄" />
    </n-form-item>
    <n-form-item label="电话号码" path="phone">
      <n-input v-model:value="formValue.phone" placeholder="电话号码" />
    </n-form-item>
    <n-form-item>
      <n-button type="primary" attr-type="button" @click="handleValidateClick"> 提交 </n-button>
    </n-form-item>
  </n-form>
  <n-modal v-model:show="showVerify" preset="card" title="验证" style="width: 360px">
    <SliderVerify v-model:id="verify.id" v-model:code="verify.code" @success="onVerifySuccess" />
  </n-modal>
</template>

<script setup>
import SliderVerify from '@/components/slider_verify.vue'
import { reactive, ref } from 'vue'
import { NForm, NFormItem, NInput, NButton, useMessage, NModal } from 'naive-ui'
import request from '@/utils/request'

const message = useMessage()

const formRef = ref(null)

const formValue = reactive({
  user: {
    name: '',
    age: ''
  },
  phone: ''
})

const rules = {
  user: {
    name: {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    },
    age: {
      required: true,
      message: '请输入年龄',
      trigger: ['input', 'blur']
    }
  },
  phone: {
    required: true,
    message: '请输入电话号码',
    trigger: ['input']
  }
}

const showVerify = ref(false)
const verify = reactive({ id: '', code: '' })

const handleValidateClick = (e) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      showVerify.value = true
    } else {
      console.log(errors)
      message.error('表单未按要求填写')
    }
  })
}

const onVerifySuccess = async () => {
  await request({
    url: '/submit',
    method: 'post',
    data: verify
  }).then((res) => {
    let data = res?.data
    if (data && data?.code == 200) {
      message.success('提交成功')
    } else {
      message.error(data.msg)
    }
  })
  showVerify.value = false
  verify.id = ''
  verify.code = ''
  formValue.user.name = ''
  formValue.user.age = ''
  formValue.phone = ''
}
</script>

<style scoped>
.n-input {
  max-width: 180px;
}
</style>
